package com.roast.services.my;

import com.roast.domain.UserData;
import com.roast.util.QueryObject;
import com.roast.util.QueryBeanFactory;

public class SingupIMPL extends GeneralSO implements Singup {

    private UserData user;
    private QueryObject queryObject;

    @Override
    public int singup(UserData user) {
        return new SingupIMPL().generalExecution(user);
    }

    @Override
    protected int executeSO(Object obj) {
        if (!setUser(obj)) {
            return 10101;
        }
        if (!user.isEmailSet()) {
            return 10102;
        }
        if (!setQuery()) {
            return 10103;
        }
        if (isUserExist()) {
            return 10104;
        }
        if (!saveUser()) {
            return 10105;
        }
        return 10100;
    }

    private boolean setUser(Object obj) {
        try {
            this.user = (UserData) obj;
            return true;
        } catch (ClassCastException ex) {
            return false;
        }
    }

    private boolean setQuery() {
        queryObject = QueryBeanFactory.getBean("readUserByParametar");
        if (queryObject != null) {
            queryObject.addParametar("femail", user.getEmail());
            return true;
        } else {
            return false;
        }
    }

    private boolean isUserExist() {
        dbbr.readOneByParametar(queryObject);
        return queryObject.getSignal() == 10030;
    }

    private boolean saveUser() {
        return dbbr.save(user);
    }

    @Override
    protected boolean executeState(int signal) {
        switch (signal) {
            case 10100:
                showOperationState(signal, "_singup: You have successfully registered.");
                return true;
            case 10101:
                showOperationState(signal, "_singup:ERROR: Class cast exception.");
                return false;
            case 10102:
                showOperationState(signal, "_singup:ERROR: You did not set user email address.");
                return false;
            case 10103:
                showOperationState(signal, "_singup:ERROR: Fail to set query.");
                return false;
            case 10104:
                showOperationState(signal, "_singup:ERROR: Try with different email address.");
                return false;
            case 10105:
                showOperationState(signal, "_singup:ERROR: User was not save in database.");
                return false;
        }
        return false;
    }
}
